package com.rongshu.view.home.fragment.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.LoginUtils;
import com.rongshu.view.home.adapter.SharePenPalWillAdapter;
import com.rongshu.view.home.contract.ShareFriendView;
import com.rongshu.view.home.entity.ShareInformation;
import com.rongshu.view.home.listener.OnItemClickListener;
import com.rongshu.view.home.listener.OnShareItemClickListener;
import com.rongshu.view.home.presenter.ShareFriendPresenter;
import com.rongshu.view.penpal.bean.PenpalResponse;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.utils.AppInstallUtils;
import com.widget.toast.ToastUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.rongshu.utils.UserInfoUtils.getUserId;

public class SharePenpalAndThirdDialog extends Dialog {
    private LinearLayout layout_pen_pal_will;
    private RecyclerView recyclerView;
    private ImageView iv_weixin, iv_weixin_friend, iv_qq, iv_qq_friend, iv_xinlang;
    private TextView other_platform;

    public SharePenpalAndThirdDialog(Context context) {
        super(context, R.style.full_width_dialog_at_screen_bottom);
        setContentView(R.layout.fragment_share_friend_dialog_view);
        initView();
    }

    private void initView() {
        iv_weixin = findViewById(R.id.iv_weixin);
        iv_weixin_friend = findViewById(R.id.iv_weixin_friend);
        iv_qq = findViewById(R.id.iv_qq);
        iv_qq_friend = findViewById(R.id.iv_qq_friend);
        iv_xinlang = findViewById(R.id.iv_xinlang);
        layout_pen_pal_will = findViewById(R.id.layout_pen_pal_will);
        other_platform = findViewById(R.id.other_platform);
        recyclerView = findViewById(R.id.pen_pal_will_recyclerview);
        findViewById(R.id.txt_cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharePenpalAndThirdDialog.this.dismiss();
            }
        });
        WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
        layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        setCanceledOnTouchOutside(true);
    }

    public static class Builder implements View.OnClickListener, OnItemClickListener, ShareFriendView {
        private Context mContext;
        //presenter
        private ShareFriendPresenter presenter = null;
        //RecyclerView item监听
        private OnShareItemClickListener mOnShareItemClickListener = null;
        //dialog消失监听
        private DialogInterface.OnDismissListener dismissListener;
        //contribute_id 文章ID/帖子ID
        private int contribute_id = 0;
        //分享渠道分类（第三方/笔友会）
        private int shareChannel = 0;
        //分享内容的类型(1文章 2帖子）
        private int type_id = 0;
        //RecyclerView 填充数据
        private List<PenpalResponse.ResponseBean> penpalwillInfoList = null;
        //manager
        private LinearLayoutManager manager = null;
        //adapter
        private SharePenPalWillAdapter mSharePenPalWillAdapter = null;
        //share type
        private static SHARE_MEDIA SHARE_TYPE;
        private SharePenpalAndThirdDialog dialog;


        public Builder(Context mContext) {
            this.mContext = mContext;
        }

        /**
         * 分享内容的类型(1文章 2帖子）
         */
        public Builder setType_id(int type_id) {
            this.type_id = type_id;
            return this;
        }

        /**
         * RecyclerView 填充数据
         */
        public Builder setPenpalwillInfoList(List<PenpalResponse.ResponseBean> list) {
            this.penpalwillInfoList = list;
            return this;
        }

        /**
         * 文章/帖子id
         */
        public Builder setContribute_id(int contribute_id) {
            this.contribute_id = contribute_id;
            return this;
        }

        /**
         * RecyclerView item监听
         */
        public Builder setOnShareItemClickListener(OnShareItemClickListener listener) {
            this.mOnShareItemClickListener = listener;
            return this;
        }

        public SharePenpalAndThirdDialog create() {
            if (dialog == null) {
                dialog = new SharePenpalAndThirdDialog(mContext);
            }
            if (presenter == null) {
                presenter = new ShareFriendPresenter(this);
            }

            manager = new LinearLayoutManager(mContext);
            manager.setOrientation(LinearLayoutManager.HORIZONTAL);
            mSharePenPalWillAdapter = new SharePenPalWillAdapter(mContext);
            mSharePenPalWillAdapter.setOnItemClickListener(this);
            dialog.recyclerView.setLayoutManager(manager);
            dialog.recyclerView.setAdapter(mSharePenPalWillAdapter);
            updateView();

            dialog.iv_weixin.setOnClickListener(this);
            dialog.iv_weixin_friend.setOnClickListener(this);
            dialog.iv_qq.setOnClickListener(this);
            dialog.iv_qq_friend.setOnClickListener(this);
            dialog.iv_xinlang.setOnClickListener(this);
            dialog.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (dismissListener != null) {
                        dismissListener.onDismiss(dialog);
                    }
                }
            });
            return dialog;
        }

        private void updateView() {
            boolean isShowPenPalWill = true;
            if (penpalwillInfoList == null || penpalwillInfoList.isEmpty()) {
                isShowPenPalWill = false;
            }
            dialog.layout_pen_pal_will.setVisibility(isShowPenPalWill ? View.VISIBLE : View.GONE);
            dialog.other_platform.setVisibility(isShowPenPalWill ? View.VISIBLE : View.GONE);
            if (isShowPenPalWill) {
                mSharePenPalWillAdapter.setSharePenpalwillInfos(penpalwillInfoList);
                mSharePenPalWillAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.iv_weixin:
                    if (AppInstallUtils.isWeixinAvilible(mContext)) {
                        SHARE_TYPE = SHARE_MEDIA.WEIXIN;
                    } else {
                        ToastUtils.show("\"微信\"不可用\n请检查手机是否安装\"微信\"");
                        return;
                    }
                    break;
                case R.id.iv_weixin_friend:
                    if (AppInstallUtils.isWeixinAvilible(mContext)) {
                        SHARE_TYPE = SHARE_MEDIA.WEIXIN_CIRCLE;
                    } else {
                        ToastUtils.show("\"微信\"不可用\n请检查手机是否安装\"微信\"");
                        return;
                    }
                    break;
                case R.id.iv_qq:
                    if (AppInstallUtils.isQQAvailable(mContext)) {
                        SHARE_TYPE = SHARE_MEDIA.QQ;
                    } else {
                        ToastUtils.show("\"QQ\"不可用\n请检查手机是否安装\"QQ\"");
                        return;
                    }
                    break;
                case R.id.iv_qq_friend:
                    if (AppInstallUtils.isQQAvailable(mContext)) {
                        SHARE_TYPE = SHARE_MEDIA.QZONE;
                    } else {
                        ToastUtils.show("\"QQ\"不可用\n请检查手机是否安装\"QQ\"");
                        return;
                    }
                    break;
                case R.id.iv_xinlang:
                    if (AppInstallUtils.isWBAvailable(mContext)) {
                        SHARE_TYPE = SHARE_MEDIA.SINA;
                    } else {
                        ToastUtils.show("\"新浪微博\"不可用\n请检查手机是否安装\"新浪微博\"");
                        return;
                    }
                    break;
            }
            //listener
            if (mOnShareItemClickListener != null) {
                mOnShareItemClickListener.onShardClick(SHARE_TYPE);
                return;
            }
            //type
            shareChannel = 2;
            //发起分享
            getAtricleDetails(0);
        }

        /**
         * 分享到笔友会
         */
        private void getAtricleDetails(int penpalwill_id) {
            //user_id
            int user_id = getUserId();
            if (user_id == 0) {
                LoginUtils.toLogin(mContext);
                return;
            }
            //http
            Map<String, Object> map = new HashMap<>();
            map.put("type", shareChannel);//(1分享到笔会 2分享到外部（QQ、微信、微博）
            map.put("contribute_id", contribute_id);//文章ID/帖子ID
            map.put("type_id", type_id);//(1文章 2帖子）
            map.put("user_id", user_id);
            map.put("penpalwill_id", penpalwill_id);
            presenter.getShareInformation(
                    (int) map.get("type"),
                    (int) map.get("contribute_id"),
                    (int) map.get("type_id"),
                    (int) map.get("user_id"),
                    (int) map.get("penpalwill_id"),
                    Common.encryptionSign(map));
        }

        private void requestShare(SHARE_MEDIA type, ShareInformation.ResponseBean responseBean) {
            final UMWeb web = new UMWeb(responseBean.getShare_link());
            web.setTitle(responseBean.getTitle());//标题
            web.setThumb(new UMImage(mContext, responseBean.getImg()));  //缩略图
            web.setDescription(responseBean.getContent());//描述
            new ShareAction((Activity) mContext)
                    .setPlatform(type)//传入平台
                    .withMedia(web)
                    .setCallback(new UMShareListener() {
                        @Override
                        public void onStart(SHARE_MEDIA share_media) {

                        }

                        @Override
                        public void onResult(SHARE_MEDIA share_media) {
                        }

                        @Override
                        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                            ToastUtils.show(throwable.getMessage());
                        }

                        @Override
                        public void onCancel(SHARE_MEDIA share_media) {
                        }
                    }).share();
        }

        @Override
        public void onShareFriend(ShareInformation information) {
            if (shareChannel == 1) {
                ToastUtils.show(information.getErrMsg());
            } else {
                requestShare(SHARE_TYPE, information.getResponse());
            }
            dialog.dismiss();
        }

        @Override
        public void onItemClick(int position) {
            if (mSharePenPalWillAdapter != null) {
                List<PenpalResponse.ResponseBean> responseBeanList = mSharePenPalWillAdapter.getSharePenpalwillInfos();
                if (responseBeanList != null && !responseBeanList.isEmpty()) {
                    //notity
                    responseBeanList.get(position).setIsselect(true);
                    mSharePenPalWillAdapter.notifyDataSetChanged();
                    //type
                    shareChannel = 1;
                    //分享到笔友会
                    getAtricleDetails(responseBeanList.get(position).getPenpalwill_id());
                }
            }
        }
    }
}
